/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package global;

import gui.DatabaseConfig;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 *
 * @author HoangTLT
 * 
 */
public class ConnectDB {
    public static Connection cn;
    
    private String url;
    private String portNumber;
    private String serverName;
    private String instanceName;
    private String databaseName;
    private String username;
    private String password;
    
    public ConnectDB(String port, String server, String instance, String database, String user, String pass){
        this.portNumber = port;
        this.serverName = server;
        this.instanceName = instance;
        this.databaseName = database;
        this.username = user;
        this.password = pass;
        this.url = "jdbc:sqlserver://" + this.serverName + ";instanceName=" + this.instanceName + ";database=" + this.databaseName;
    }
    
    public void openConnection(){
        if(cn == null){
            try{
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                cn = DriverManager.getConnection(url, username, password);
                if(cn != null){
                    //System.out.println("Connection successful");
                    JOptionPane.showMessageDialog(null, "Connect to database successful!");
                }
                }catch (SQLException ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null, "Can not find the specific jdbc driver for SQL Server!");
                    LoggerInfo.Error("Cannot Connect to database : ", " show Connection Configure");
                new DatabaseConfig().setVisible(true);
                }catch (ClassNotFoundException ex){
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null, "Can not find the specific jdbc driver for SQL Server!");
                      LoggerInfo.Error("Cannot Connect to database : ", " show Connection Configure");
                new DatabaseConfig().setVisible(true);
                }
        }
    }
    
    //disconnect from database
    public void closeConnection(){
        if(cn != null){
            try{
                cn.close();
                cn = null;
                System.out.println("Disconnect sucessfull!");
            }catch(SQLException ex){
                ex.printStackTrace();
            }
        }
    }
}
